package com.appspot.menox3secandroid2011.service;

import java.util.List;
import java.util.logging.Logger;

import org.slim3.datastore.Datastore;

import com.appspot.menox3secandroid2011.meta.C2dmInfoMeta;
import com.appspot.menox3secandroid2011.model.C2dmInfo;
import com.google.appengine.api.datastore.Key;

public class C2DMRegister {
    private static Logger logger = Logger.getLogger("C2DMRegister");
    public void setRegisterInfo(String regID, String senderID){
        logger.info("registerInfo() regID: " + regID + " senderID: " + senderID);

        C2dmInfo c2dm_tbl = new C2dmInfo();

        C2dmInfoMeta c2dmMeta = C2dmInfoMeta.get();

        List<C2dmInfo> dataList = Datastore.query(c2dmMeta)
        .filter(c2dmMeta.senderID.equal(senderID))
        .asList();
        if(dataList.size() > 0){
            logger.info("Update");
            Key key = dataList.get(0).getKey();
            Long version  = dataList.get(0).getVersion();
            C2dmInfo model = Datastore.get(c2dmMeta, key, version);
            model.setRegistrationID(regID);
            model.setSenderID(senderID);
            Datastore.put(model);
        } else {
            logger.info("New");
            c2dm_tbl.setRegistrationID(regID);
            c2dm_tbl.setSenderID(senderID);
            Datastore.put(c2dm_tbl);
        }
    }

    public String getRegisterInfo(String senderID){
        C2dmInfoMeta c2dmMeta = C2dmInfoMeta.get();
        logger.info("getRegisterInfo senderID" + senderID);
        List<C2dmInfo> dataList = Datastore.query(c2dmMeta)
        .filter(c2dmMeta.senderID.equal(senderID))
        .asList();
        if(dataList.size() > 0){
            String getReg = dataList.get(0).getRegistrationID();
            logger.info("getRegisterInfo get register " + getReg);
            return getReg;
        } else {
            logger.info("getRegisterInfo no register " + senderID);
            return null;
        }
    }

    public void unregisterInfo(String senderID){
        logger.info("unregisterInfo() senderID" + senderID);
        C2dmInfoMeta c2dmMeta = C2dmInfoMeta.get();
        List<C2dmInfo> dataList = Datastore.query(c2dmMeta)
        .filter(c2dmMeta.senderID.equal(senderID))
        .asList();
        if(dataList.size() > 0){
            logger.info("Delete");
            Key key = dataList.get(0).getKey();
            Datastore.delete(key);
        }
    }

//    private void addData(String regID, String senderID) {
//        logger.info("addData() regID: " + regID + " senderID: " + senderID);
//    }

}
